package com.haibei.adapter;

import java.util.ArrayList;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.haibei.R;
import com.haibei.adapter.bean.ContentItem;
import com.haibei.cache.list.ImageManagerLru;

public class ArticleContentAdapter extends BaseAdapter {

	private Activity mActivity;
	private ArrayList<ContentItem> mArrayListItems;

	public ArticleContentAdapter(Activity activity, ArrayList<ContentItem> items) {
		this.mActivity = activity;
		this.mArrayListItems = items;
	}

	@Override
	public int getCount() {
		return mArrayListItems.size();
	}

	@Override
	public Object getItem(int pos) {
		return mArrayListItems.get(pos);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		ViewHolderImg vi = null;
		ViewHolderText vt = null;
		ContentItem ab = mArrayListItems.get(position);

		int itype = getItemViewType(position);
		if (null == convertView) {
			switch (itype) {
			case type_img:
				vi = new ViewHolderImg();
				convertView = View.inflate(mActivity, R.layout.item_detail_article_img, null);
				vi.imageView = (ImageView) convertView.findViewById(R.id.imageViewPic);
				convertView.setTag(vi);
				break;
			case type_text:
				vt = new ViewHolderText();
				convertView = View.inflate(mActivity, R.layout.item_detail_article_text, null);
				vt.textView = (TextView) convertView.findViewById(R.id.textViewText);
				convertView.setTag(vt);
				break;
			}
		} else {
			switch (itype) {
			case type_text:
				vt = (ViewHolderText) convertView.getTag();
				break;
			case type_img:
				vi = (ViewHolderImg) convertView.getTag();
				break;
			}
		}
		switch (itype) {
		case type_text:
			vt.textView.setText("    "+ab.getContent().replace("<<br/>>", "\n").replace(" ", ""));
			break;
		case type_img:
			String url = ab.getContent();
			ImageManagerLru.from(mActivity).displayImage(vi.imageView, url, R.drawable.bg_default_article,true);
			break;
		}
		return convertView;
	}

	class ViewHolderImg {
		ImageView imageView;
	}

	class ViewHolderText {
		TextView textView;
	}

	@Override
	public int getItemViewType(int position) {
		ContentItem ab = mArrayListItems.get(position);
		if (ab.isImg()) {
			return type_img;
		} else {
			return type_text;
		}
	}

	@Override
	public int getViewTypeCount() {
		return 3;
	}

	private final int type_text = 1;
	private final int type_img = 2;
}
